package src.serverSide;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

import src.messagesToServer.MessageToServer;

/**
 * The class to handle the clients
 * @author John Stewart
 */
public class Handler implements Runnable {
	private Socket client;
	private Control control;
	
	public Handler(Socket client, Control control) {
		this.client = client;
		this.control = control;
	}

	/**
	 * This method handles the messages from the client, and responds with another message
	 */
	@Override
	public void run() {
		String address = null;
		try {
			System.out.println("Client Conected");
			address = client.getInetAddress().getHostAddress();
			ObjectInputStream in = new ObjectInputStream(client.getInputStream());
			ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
			boolean notdone = true;
			while (notdone) {
				Object message = in.readObject();
				if (message instanceof MessageToServer)
					out.writeObject(((MessageToServer) message).execute(address, control));
				else notdone = false;
			}
			client.close();
		} catch (IOException e) {
			System.out.println("Detected Client Disconnect");
			control.logout(address);
		} catch (ClassNotFoundException e) {
			System.out.println("Error: In Client Handler");
			e.printStackTrace();
		}
	}

}
